package com.yearno.baseframe.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.yearno.baseframe.databinding.BaseFragmentBinding
import com.yearno.baseframe.dialog.LoadingDialogFragment

abstract class BaseFragment<VB : ViewBinding, VM : BaseViewModel> : Fragment() {

    private var isViewOK = false //是否完成 View 初始化
    private var isFirst = true //是否为第一次加载
    var baseBinding: BaseFragmentBinding? = null
    var viewBinding: VB? = null
    protected abstract fun getVB(): VB

    abstract fun viewModel(): Class<VM>

    abstract fun initViewModel(vm: VM)

    /**
     * fragment 初始化 view 的方法
     */
    abstract fun initView()

    /**
     * fragment 实现懒加载的方法，即在这里加载数据
     */
    abstract fun loadDate()

    private val mLoadingDialog: LoadingDialogFragment by lazy {
        LoadingDialogFragment()
    }

    private fun showLoading() {
        if (!mLoadingDialog.isAdded) {
            activity?.supportFragmentManager?.let {
                mLoadingDialog.showDialog(it)
            }
        }
    }

    private fun dismissLoading() {
        if (mLoadingDialog.isVisible) {
            mLoadingDialog.dismiss()
        }
    }

    private fun initBaseViewModel(vm: BaseViewModel) {
        vm.mLoadingLD.observe(viewLifecycleOwner, {
            if (it.isShow) {
                showLoading()
            } else {
                dismissLoading()
            }
        })
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (baseBinding == null) {
            baseBinding = BaseFragmentBinding.inflate(layoutInflater)
            viewBinding = getVB()
            initView()
            val vm = ViewModelProvider(this).get(viewModel())
            initBaseViewModel(vm)
            initViewModel(vm)
            isViewOK = true
        }
        return baseBinding?.root
    }

    override fun onResume() {
        super.onResume()
        if (isViewOK && isFirst) {
            //加载数据时判断是否完成view的初始化，以及是不是第一次加载此数据
            loadDate()
            //加载第一次数据后改变状态，后续不再重复加载
            isFirst = false
        }
    }

    //释放数据
    override fun onDestroyView() {
        super.onDestroyView()
        baseBinding = null
        viewBinding = null
    }
}